{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "4embtkV0pNxM"
   },
   "source": [
    "Deep Learning\n",
    "=============\n",
    "\n",
    "Assignment 4\n",
    "------------\n",
    "\n",
    "Previously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters.\n",
    "\n",
    "The goal of this assignment is make the neural network convolutional."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "tm2CQN_Cpwj0"
   },
   "outputs": [],
   "source": [
    "# These are all the modules we'll be using later. Make sure you can import them\n",
    "# before proceeding further.\n",
    "from __future__ import print_function\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from six.moves import cPickle as pickle\n",
    "from six.moves import range"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11948,
     "status": "ok",
     "timestamp": 1446658914837,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "y3-cj1bpmuxc",
    "outputId": "016b1a51-0290-4b08-efdb-8c95ffc3cd01"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 28, 28) (200000,)\n",
      "Validation set (10000, 28, 28) (10000,)\n",
      "Test set (10000, 28, 28) (10000,)\n"
     ]
    }
   ],
   "source": [
    "pickle_file = 'notMNIST.pickle'\n",
    "\n",
    "with open(pickle_file, 'rb') as f:\n",
    "  save = pickle.load(f)\n",
    "  train_dataset = save['train_dataset']\n",
    "  train_labels = save['train_labels']\n",
    "  valid_dataset = save['valid_dataset']\n",
    "  valid_labels = save['valid_labels']\n",
    "  test_dataset = save['test_dataset']\n",
    "  test_labels = save['test_labels']\n",
    "  del save  # hint to help gc free up memory\n",
    "  print('Training set', train_dataset.shape, train_labels.shape)\n",
    "  print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "  print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "L7aHrm6nGDMB"
   },
   "source": [
    "Reformat into a TensorFlow-friendly shape:\n",
    "- convolutions need the image data formatted as a cube (width by height by #channels)\n",
    "- labels as float 1-hot encodings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11952,
     "status": "ok",
     "timestamp": 1446658914857,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "IRSyYiIIGIzS",
    "outputId": "650a208c-8359-4852-f4f5-8bf10e80ef6c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 28, 28, 1) (200000, 10)\n",
      "Validation set (10000, 28, 28, 1) (10000, 10)\n",
      "Test set (10000, 28, 28, 1) (10000, 10)\n"
     ]
    }
   ],
   "source": [
    "image_size = 28\n",
    "num_labels = 10\n",
    "num_channels = 1 # grayscale\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "def reformat(dataset, labels):\n",
    "  dataset = dataset.reshape(\n",
    "    (-1, image_size, image_size, num_channels)).astype(np.float32)\n",
    "  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n",
    "  return dataset, labels\n",
    "train_dataset, train_labels = reformat(train_dataset, train_labels)\n",
    "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n",
    "test_dataset, test_labels = reformat(test_dataset, test_labels)\n",
    "print('Training set', train_dataset.shape, train_labels.shape)\n",
    "print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "AgQDIREv02p1"
   },
   "outputs": [],
   "source": [
    "def accuracy(predictions, labels):\n",
    "  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n",
    "          / predictions.shape[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "5rhgjmROXu2O"
   },
   "source": [
    "Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "IZYv70SvvOan"
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data.\n",
    "  tf_train_dataset = tf.placeholder(\n",
    "    tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "  # Variables.\n",
    "  layer1_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "  layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "  layer2_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "  layer3_weights = tf.Variable(tf.truncated_normal(\n",
    "      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))\n",
    "  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "  layer4_weights = tf.Variable(tf.truncated_normal(\n",
    "      [num_hidden, num_labels], stddev=0.1))\n",
    "  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "  # Model.\n",
    "  def model(data):\n",
    "    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(conv + layer1_biases)\n",
    "    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(conv + layer2_biases)\n",
    "    shape = hidden.get_shape().as_list()\n",
    "    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "    return tf.matmul(hidden, layer4_weights) + layer4_biases\n",
    "  \n",
    "  # Training computation.\n",
    "  logits = model(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 37
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 63292,
     "status": "ok",
     "timestamp": 1446658966251,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "noKFb2UovVFR",
    "outputId": "28941338-2ef9-4088-8bd1-44295661e628"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 3.139105\n",
      "Minibatch accuracy: 12.5%\n",
      "Validation accuracy: 11.9%\n",
      "Minibatch loss at step 100: 1.115680\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 67.1%\n",
      "Minibatch loss at step 200: 0.356532\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 78.4%\n",
      "Minibatch loss at step 300: 0.310974\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 78.7%\n",
      "Minibatch loss at step 400: 0.602386\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 79.5%\n",
      "Minibatch loss at step 500: 0.441770\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 81.2%\n",
      "Minibatch loss at step 600: 0.840172\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 82.3%\n",
      "Minibatch loss at step 700: 1.235861\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 82.9%\n",
      "Minibatch loss at step 800: 0.885891\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 82.5%\n",
      "Minibatch loss at step 900: 0.300222\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 82.6%\n",
      "Minibatch loss at step 1000: 0.506481\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 84.0%\n",
      "Test accuracy: 90.1%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 1001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print('Initialized')\n",
    "  for step in range(num_steps):\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "    if (step % 100 == 0):\n",
    "      print('Minibatch loss at step %d: %f' % (step, l))\n",
    "      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "      print('Validation accuracy: %.1f%%' % accuracy(\n",
    "        valid_prediction.eval(), valid_labels))\n",
    "  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KedKkn4EutIK"
   },
   "source": [
    "---\n",
    "Problem 1\n",
    "---------\n",
    "\n",
    "The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (`nn.max_pool()`) of stride 2 and kernel size 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data.\n",
    "  tf_train_dataset = tf.placeholder(\n",
    "    tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "  # Variables.\n",
    "  layer1_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "  layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "  layer2_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "  layer3_weights = tf.Variable(tf.truncated_normal(\n",
    "      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))\n",
    "  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "  layer4_weights = tf.Variable(tf.truncated_normal(\n",
    "      [num_hidden, num_labels], stddev=0.1))\n",
    "  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "  # Model.\n",
    "  def model(data):\n",
    "    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')\n",
    "    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(pool + layer1_biases)\n",
    "    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')\n",
    "    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(pool + layer2_biases)\n",
    "    shape = hidden.get_shape().as_list()\n",
    "    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "    return tf.matmul(hidden, layer4_weights) + layer4_biases\n",
    "  \n",
    "  # Training computation.\n",
    "  logits = model(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 2.883915\n",
      "Minibatch accuracy: 12.5%\n",
      "Validation accuracy: 10.0%\n",
      "Minibatch loss at step 100: 1.051122\n",
      "Minibatch accuracy: 56.2%\n",
      "Validation accuracy: 59.1%\n",
      "Minibatch loss at step 200: 0.415176\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 76.4%\n",
      "Minibatch loss at step 300: 0.316238\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 81.7%\n",
      "Minibatch loss at step 400: 0.553747\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 80.0%\n",
      "Minibatch loss at step 500: 0.250361\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 81.5%\n",
      "Minibatch loss at step 600: 0.627140\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 83.7%\n",
      "Minibatch loss at step 700: 1.068274\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 84.3%\n",
      "Minibatch loss at step 800: 0.719155\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 83.8%\n",
      "Minibatch loss at step 900: 0.629290\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 84.5%\n",
      "Minibatch loss at step 1000: 0.510888\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 84.2%\n",
      "Test accuracy: 89.8%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 1001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print('Initialized')\n",
    "  for step in range(num_steps):\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "    if (step % 100 == 0):\n",
    "      print('Minibatch loss at step %d: %f' % (step, l))\n",
    "      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "      print('Validation accuracy: %.1f%%' % accuracy(\n",
    "        valid_prediction.eval(), valid_labels))\n",
    "  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "klf21gpbAgb-"
   },
   "source": [
    "---\n",
    "Problem 2\n",
    "---------\n",
    "\n",
    "Try to get the best performance you can using a convolutional net. Look for example at the classic [LeNet5](http://yann.lecun.com/exdb/lenet/) architecture, adding Dropout, and/or adding learning rate decay."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "  # Input data.\n",
    "  tf_train_dataset = tf.placeholder(\n",
    "    tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "  tf_valid_dataset = tf.constant(valid_dataset)\n",
    "  tf_test_dataset = tf.constant(test_dataset)\n",
    "\n",
    "  # Placeholder to control dropout probability.\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  \n",
    "  # Variables.\n",
    "  layer1_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "  layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "  layer2_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "  layer3_weights = tf.Variable(tf.truncated_normal(\n",
    "      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))\n",
    "  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "  layer4_weights = tf.Variable(tf.truncated_normal(\n",
    "      [num_hidden, num_labels], stddev=0.1))\n",
    "  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "  # Model.\n",
    "  def model(data):\n",
    "    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')\n",
    "    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(pool + layer1_biases)\n",
    "    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')\n",
    "    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "    hidden = tf.nn.relu(pool + layer2_biases)\n",
    "    shape = hidden.get_shape().as_list()\n",
    "    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "    drop = tf.nn.dropout(hidden, keep_prob)\n",
    "    return tf.matmul(drop, layer4_weights) + layer4_biases\n",
    "  \n",
    "  # Training computation.\n",
    "  logits = model(tf_train_dataset)\n",
    "  loss = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "  # Optimizer.\n",
    "  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "  # Predictions for the training, validation, and test data.\n",
    "  train_prediction = tf.nn.softmax(logits)\n",
    "  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "  test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 4.529957\n",
      "Minibatch accuracy: 18.8%\n",
      "Validation accuracy: 12.3%\n",
      "Minibatch loss at step 100: 1.826838\n",
      "Minibatch accuracy: 50.0%\n",
      "Validation accuracy: 46.1%\n",
      "Minibatch loss at step 200: 1.026006\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 69.2%\n",
      "Minibatch loss at step 300: 0.719998\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 76.9%\n",
      "Minibatch loss at step 400: 1.125187\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 78.8%\n",
      "Minibatch loss at step 500: 0.659142\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 80.9%\n",
      "Minibatch loss at step 600: 1.144517\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 81.3%\n",
      "Minibatch loss at step 700: 1.284646\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 81.7%\n",
      "Minibatch loss at step 800: 1.318694\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 82.3%\n",
      "Minibatch loss at step 900: 0.596128\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.2%\n",
      "Minibatch loss at step 1000: 0.593340\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.5%\n",
      "Minibatch loss at step 1100: 1.036340\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.8%\n",
      "Minibatch loss at step 1200: 0.578478\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 84.5%\n",
      "Minibatch loss at step 1300: 1.571593\n",
      "Minibatch accuracy: 43.8%\n",
      "Validation accuracy: 83.8%\n",
      "Minibatch loss at step 1400: 0.659016\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 84.5%\n",
      "Minibatch loss at step 1500: 0.455753\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 84.9%\n",
      "Minibatch loss at step 1600: 0.458268\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 84.5%\n",
      "Minibatch loss at step 1700: 0.856795\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 84.9%\n",
      "Minibatch loss at step 1800: 0.423227\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 85.0%\n",
      "Minibatch loss at step 1900: 0.750963\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 84.8%\n",
      "Minibatch loss at step 2000: 0.760005\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 85.4%\n",
      "Minibatch loss at step 2100: 0.779080\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 85.5%\n",
      "Minibatch loss at step 2200: 0.371877\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 85.4%\n",
      "Minibatch loss at step 2300: 0.551173\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 85.1%\n",
      "Minibatch loss at step 2400: 0.251618\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 86.0%\n",
      "Minibatch loss at step 2500: 1.167190\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 84.7%\n",
      "Minibatch loss at step 2600: 1.088484\n",
      "Minibatch accuracy: 56.2%\n",
      "Validation accuracy: 85.0%\n",
      "Minibatch loss at step 2700: 0.663480\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 85.2%\n",
      "Minibatch loss at step 2800: 0.869098\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 86.3%\n",
      "Minibatch loss at step 2900: 0.405881\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 86.4%\n",
      "Minibatch loss at step 3000: 0.435097\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 86.0%\n",
      "Test accuracy: 92.1%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 3001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "  tf.initialize_all_variables().run()\n",
    "  print('Initialized')\n",
    "  for step in range(num_steps):\n",
    "    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "    batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 1.0}\n",
    "    feed_dict_w_drop = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: 0.5}\n",
    "    _, l, predictions = session.run(\n",
    "      [optimizer, loss, train_prediction], feed_dict=feed_dict_w_drop)\n",
    "    if (step % 100 == 0):\n",
    "      print('Minibatch loss at step %d: %f' % (step, l))\n",
    "      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "      print('Validation accuracy: %.1f%%' % accuracy(\n",
    "        valid_prediction.eval(feed_dict=feed_dict), valid_labels))\n",
    "  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict=feed_dict), test_labels))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "default_view": {},
   "name": "4_convolutions.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
